package tc.jv.task11;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import tc.jv.task4.Vector;
import tc.jv.task8.Vectors;

public class Client
{

	private static final String name = "Client> "; 
	
	public final int port;
	public final String address = "127.0.0.1";
	private Socket socket;
	
	public Client(int port)
	{
		this.port = port;
		
		InetAddress ipAddress;
		try
		{
			ipAddress = InetAddress.getByName(address);
			socket = new Socket(ipAddress, port);
			System.out.println(name + "Connected");
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}	
	}
	
	@Override
	protected void finalize() throws Throwable
	{
		super.finalize();
		socket.close();
		System.out.println(name + "Closed.");
	}
	
	public static Vector sumVectors(Vector v1, Vector v2)
	{
		Client c = new Client(12011);
		Vector result = null;
		try
		{
			InputStream   in = c.socket.getInputStream();
			OutputStream out = c.socket.getOutputStream();
			
			System.out.println(name + "Sending...");
			v1.print(1);
			Vectors.outputVector(v1, out);
			v2.print(1);
			Vectors.outputVector(v2, out);

			result = Vectors.inputVector(in);
			System.out.println(name + "Received: ");
			result.print(1);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	public static void main(String[] args)
	{
		String CURRENT_PATH = "E:\\workspace\\NetCracker\\src\\tc\\"
							+ "jv\\task11\\";
		
		String input  = args[0],
			   output = args[1];
		
		Vector v1, v2, result;
		
		FileWriter fw = null;
		FileReader fr = null;
		try
		{
			fr = new FileReader(CURRENT_PATH + input);
			fw = new FileWriter(CURRENT_PATH + output);
			
			while (fr.ready())
			{
				v1     = null;
				v2     = null;
				result = null;
				
				System.out.println("Source data: ");
				v1 = Vectors.readVector(fr);
				v1.print(1);
				v2 = Vectors.readVector(fr);
				v2.print(1);
				
				if (v2.size() == 0)
				{
					System.err.println("Error: Нечетное количество векторов!");
					throw new IllegalArgumentException();
				}
				
				result = sumVectors(v1, v2);
				
				Vectors.writeVector(result, fw);
				fw.flush();
				
				System.out.println("-------------------------");
			}
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try {fw.close(); fr.close();} catch (IOException e) {e.printStackTrace();}
		}
	}
}
